﻿using System;
using System.Linq;
using System.Text;
using CLDataAppManagement;
using ControlzEx.Standard;
using DataFileApplication_WPF.Models;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using System.Windows;
using System.Collections.ObjectModel;
using DataFileApplication_WPF.Views;
using System.Reflection;
using System.IO;
using DataFileApplication_WPF.Extensions;
using DataFileApplication_WPF.Commands;
using DataFileApplication_WPF.Helper;
using System.Globalization;
using Newtonsoft.Json.Schema;
using DataFileApplication_WPF.Common;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using Newtonsoft.Json;



namespace DataFileApplication_WPF.ViewModels
{
    public class MainViewModel : NotifyPropertyChangedBase
    {

        DataAppManagement dataAppManagement = new DataAppManagement();
        JToken jToken = null;
        JToken saveJtoken = null;
        //string filePath = string.Empty;

        //数据做显示用
        private TreeItemStruct _treeItemInstance;
        public TreeItemStruct TreeItemInstance
        {
            get { return _treeItemInstance; }
            set
            {
                _treeItemInstance = value;
                this.RaisePropertyChanged();
            }
        }

        //选中的树节点
        private TreeItemStruct _treeItemSelected;
        public TreeItemStruct TreeItemSelected
        {
            get { return _treeItemSelected; }
            set
            {
                if (_treeItemSelected != value)
                {
                    _treeItemSelected = value;
                    this.RaisePropertyChanged();
                    //触发  判断右键菜单功能的可用性
                    //  AddTreeItemCommand?.RaiseCanExecuteChanged();
                }
            }
        }

        //选中的树节点中含有的表格数据
        private DataGridStruct _dataGridStructSelected;
        public DataGridStruct DataGridStructSelected
        {
            get { return _dataGridStructSelected; }
            set
            {
                _dataGridStructSelected = value;
                this.RaisePropertyChanged();
            }
        }


        //选中的表格数据中的单行数据
        private DataGridItemStruct _dataGridItemSelected;

        public DataGridItemStruct DataGridItemSelected
        {
            get { return _dataGridItemSelected; }
            set
            {
                _dataGridItemSelected = value;
                this.RaisePropertyChanged();
            }
        }

        //选中的表格数据中的单行数据   用来存储编辑的数据
        private DataGridItemStruct _dataGridItemSelectedForEdit;

        public DataGridItemStruct DataGridItemSelectedForEdit
        {
            get { return _dataGridItemSelectedForEdit; }
            set
            {
                _dataGridItemSelectedForEdit = value;
                this.RaisePropertyChanged();
            }
        }

        //选中的表格数据中的单行数据的多语言备注
        private string _dataGridItemSelectedLanguage;
        public string DataGridItemSelectedLanguage
        {

            get { return _dataGridItemSelectedLanguage; }
            set
            {

                _dataGridItemSelectedLanguage = value;
                this.RaisePropertyChanged();
            }
        }

        //private string _viewTitle;
        //public string ViewTitle
        //{
        //    get { return _viewTitle; }
        //    set
        //    {
        //        if (_viewTitle != value)
        //        {
        //            _viewTitle = value;
        //            this.RaisePropertyChanged();
        //        }
        //    }
        //}

        //判断是否选中树节点
        public bool IsTreeItemSelected => TreeItemSelected != null && TreeItemSelected.Parent != null;


        //判断数据   的ContentControl的数据有效性
        private bool _dataTemplateValid;

        public bool DataTemplateValid
        {
            get { return _dataTemplateValid; }
            set { _dataTemplateValid = value; this.RaisePropertyChanged(); }
        }



        public List<bool> BoolList
        {
            get
            {
                return new List<Boolean>() { true, false };
            }
        }

        private string _filePath;

        public string FilePath
        {
            get
            {
                if (string.IsNullOrEmpty(_filePath))
                {
                    return "New File -DataFileApp";
                }
                return _filePath;
            }
            set { _filePath = value; this.RaisePropertyChanged(); }
        }


        //****************************  Command  *************************************
        //*****  菜单栏  *********
        public DelegateCommand NewFileCommand { get; set; }
        public DelegateCommand OpenFileCommand { get; set; }
        public DelegateCommand SaveFileCommand { get; set; }
        public DelegateCommand SaveFileAsCommand { get; set; }

        public DelegateCommand OperaterLanguageCommand { get; set; }
        public DelegateCommand ChineseLanguageCommand { get; set; }
        public DelegateCommand EnglishLanguageCommand { get; set; }
        public DelegateCommand GermanLanguageCommand { get; set; }

        public DelegateCommand VersionCommand { get; set; }

        //*****  TreeView  *********
        public DelegateCommand AddTreeItemCommand { get; set; }
        public DelegateCommand AddTreeChildItemCommand { get; set; }
        public DelegateCommand AddArrayTreeItemCommand { get; set; }
        public DelegateCommand AddChildArrayTreeItemCommand { get; set; }
        public DelegateCommand CopyTreeItemCommand { get; set; }
        public DelegateCommand PasteAsTreeItemCommand { get; set; }
        public DelegateCommand PasteAsChildTreeItemCommand { get; set; }
        public DelegateCommand RenameTreeItemCommand { get; set; }
        public DelegateCommand DeleteTreeItemCommand { get; set; }
        public DelegateCommand MoveUpTreeItemCommand { get; set; }
        public DelegateCommand MoveDownTreeItemCommand { get; set; }


        //********  DataGrid  *******
        public DelegateCommand AddDataGridItemCommand { get; set; }
        public DelegateCommand CopyDataGridItemCommand { get; set; }
        public DelegateCommand PasteDataGridItemCommand { get; set; }
        public DelegateCommand DeleteDataGridItemCommand { get; set; }
        public DelegateCommand MoveUpDataGridItemCommand { get; set; }
        public DelegateCommand MoveDownDataGridItemCommand { get; set; }

        //*************************
        public DelegateCommand EditValueListCommand { get; set; }
        public DelegateCommand ConfirmCommand { get; set; }

        public DelegateCommandParameter LoadFileCommand { get; set; }


        //文件加载完成快照json，用来判断文件是否被修改
        private string originalJsonStr = "";

        //文件是否被修改
        bool _isFileModified = false;
        public bool IsFileModified
        {
            get { return _isFileModified; }
            set { _isFileModified = value; this.RaisePropertyChanged(); }
        }


        // 加载或保存后，记录快照
        private void UpdateOriginalJsonStr()
        {
            //JToken saveJtoken = new JObject();
            //TraverseTreeItem(TreeItemInstance, saveJtoken);
            //originalJsonStr = JsonConvert.SerializeObject(saveJtoken);
            //UpdateFormTitle();
        }

        private void UpdateFormTitle(bool isSave = false)
        {
            //if (isSave)
            //{
            //    if (this.FilePath.EndsWith("*"))
            //        this.FilePath = this.FilePath.TrimEnd('*');
            //    IsFileModified = false;
            //    return;
            //}

            //JToken saveJtoken = new JObject();
            //TraverseTreeItem(TreeItemInstance, saveJtoken);
            //string currentJsonStr = JsonConvert.SerializeObject(saveJtoken);

            //if (currentJsonStr != originalJsonStr)
            //{
            //    if (!this.FilePath.EndsWith("*"))
            //        this.FilePath += "*";
            //    IsFileModified = true;
            //}
            //else
            //{
            //    if (this.FilePath.EndsWith("*"))
            //        this.FilePath = this.FilePath.TrimEnd('*');
            //    IsFileModified = false;
            //}
        }



        public MainViewModel()
        {
            //FilePath = "New File -DataFileApp";

            LoadFileCommand = new DelegateCommandParameter((e) =>
            {
                jToken = dataAppManagement.LoadFile(FilePath, out int ErrorCode, out string ErrorText);
                if (ErrorCode == -1)
                {
                    MessageBox.Show(ErrorText);
                    FilePath = string.Empty;
                    return;
                }
                _treeItemInstance = new TreeItemStruct();
                AddJTokenToTreeView(jToken, ref _treeItemInstance, out ErrorCode, out ErrorText);
                TreeItemInstance = _treeItemInstance;
                UpdateOriginalJsonStr();
            });

            //********************************  菜单栏  **********************
            //新建文件
            NewFileCommand = new DelegateCommand((e) =>
          {
              TreeItemInstance = new TreeItemStruct();
              TreeItemStruct childItem = new TreeItemStruct();
              childItem.Name = "Root";
              childItem.IconName = null;
              childItem.Parent = TreeItemInstance;
              TreeItemInstance.Children.Add(childItem);
              FilePath = string.Empty;
              UpdateOriginalJsonStr();
          });

            //打开文件
            OpenFileCommand = new DelegateCommand((e) =>
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "所有文件|*.*|cdat文件|*.cdat ";

                if (openFileDialog.ShowDialog() == true)
                {
                    string path = openFileDialog.FileName;
                    jToken = dataAppManagement.LoadFile(path, out int ErrorCode, out string ErrorText);

                    if (ErrorCode == -1)
                    {
                        MessageBox.Show(ErrorText);
                        FilePath = string.Empty;
                        return;
                    }
                    _treeItemInstance = new TreeItemStruct();
                    AddJTokenToTreeView(jToken, ref _treeItemInstance, out ErrorCode, out ErrorText);
                    TreeItemInstance = _treeItemInstance;
                    FilePath = openFileDialog.FileName;
                    //深度复制一份，确认更改数据后，将修改后的数据赋值给TreeItemInstanceForSave
                    // TreeItemInstanceForSave = TreeItemInstance.Clone();
                    UpdateOriginalJsonStr();
                }
            });

            //保存文件
            SaveFileCommand = new DelegateCommand((e) =>
            {
                try
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "所有文件|*.*|cdat文件|*.cdat ";
                    saveJtoken = new JObject();
                    //TraverseTreeItem(TreeItemInstanceForSave, saveJtoken);
                    TraverseTreeItem(TreeItemInstance, saveJtoken);

                    SaveFile(FilePath, saveJtoken, out _, out _);
                    UpdateOriginalJsonStr();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //文件另存为
            SaveFileAsCommand = new DelegateCommand((e) =>
            {
                try
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "所有文件|*.*|cdat文件|*.cdat ";
                    if (saveFileDialog.ShowDialog() == true)
                    {
                        string savePath = saveFileDialog.FileName;
                        saveJtoken = new JObject();

                        TraverseTreeItem(TreeItemInstance, saveJtoken);
                        SaveFile(savePath, saveJtoken, out _, out _); //File.AppendAllText(savePath, saveJtoken.ToString(),);

                        //若路径为空（新建的文件），则将另存的路径当作当前路径
                        if (FilePath == "New File -DataFileApp")
                        {
                            FilePath = savePath;
                        }
                        UpdateOriginalJsonStr();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            // OperaterLanguageCommand = new DelegateCommand();
            ChineseLanguageCommand = new DelegateCommand((e) =>
            {
                LanguageManager.CurrentCulture = new CultureInfo("zh-CN");
                DataGridItemSelectedLanguage = DataGridItemSelected?.DataGridComments.LanguageComments.LanguageCommentsDic["zh-CN"];
            });
            EnglishLanguageCommand = new DelegateCommand((e) =>
            {
                LanguageManager.CurrentCulture = new CultureInfo("en-US");
                DataGridItemSelectedLanguage = DataGridItemSelected?.DataGridComments.LanguageComments.LanguageCommentsDic["en-US"];
            });
            GermanLanguageCommand = new DelegateCommand((e) =>
            {
                LanguageManager.CurrentCulture = new CultureInfo("de-DE");
                DataGridItemSelectedLanguage = DataGridItemSelected?.DataGridComments.LanguageComments.LanguageCommentsDic["de-DE"];
            });

            VersionCommand = new DelegateCommand((e) =>
            {
                Version version = Assembly.GetExecutingAssembly().GetName().Version;
                VersionViewModel versionViewModel = new VersionViewModel()
                {
                    Title = "DataFileApp",
                    Company = "Chenling Optics",
                    Version = version.ToString(),
                    Comment = "The software is used to modify and save parameters"
                };
                VersionView versionView = new VersionView(versionViewModel);

                ViewShowPosition.SetShowPosition(versionView).ShowDialog();

                //versionView.ShowDialog();
            });




            //********************************  TreeView  **********************

            // 增加树节点
            AddTreeItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    if (TreeItemSelected != null)
                    {
                        AddTreeItemView addTreeItemView = new AddTreeItemView();
                        addTreeItemView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        ViewShowPosition.SetShowPosition(addTreeItemView).ShowDialog();
                        if (addTreeItemView.DialogResult != true)
                        {
                            return;
                        }

                        //从ViewModel 获取输入的名称
                        AddTreeItemViewModel addTreeItemViewModel = addTreeItemView.DataContext as AddTreeItemViewModel;
                        string newName = addTreeItemViewModel.NewName;

                        //判断当前节点下有无节点
                        if (TreeItemSelected.Children == null)
                        {
                            TreeItemSelected.Children = new ObservableCollection<TreeItemStruct>();
                        }
                        TreeItemStruct treeItem = new TreeItemStruct { Name = $"{newName}" };
                        treeItem.Parent = TreeItemSelected.Parent;
                        treeItem.IconName = null;
                        TreeItemSelected.Parent.Children.Add(treeItem);
                        UpdateFormTitle();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            // 增加子树节点
            AddTreeChildItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    if (TreeItemSelected != null)
                    {
                        AddTreeItemView addTreeItemView = new AddTreeItemView();
                        addTreeItemView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        ViewShowPosition.SetShowPosition(addTreeItemView).ShowDialog();
                        if (addTreeItemView.DialogResult != true)
                        {
                            return;
                        }

                        //从ViewModel 获取输入的名称
                        AddTreeItemViewModel addTreeItemViewModel = addTreeItemView.DataContext as AddTreeItemViewModel;
                        string newName = addTreeItemViewModel.NewName;

                        if (TreeItemSelected.Children == null)
                        {
                            TreeItemSelected.Children = new ObservableCollection<TreeItemStruct>();
                        }
                        TreeItemStruct treeItem = new TreeItemStruct { Name = $"{newName}" };
                        treeItem.Parent = TreeItemSelected;
                        treeItem.IconName = null;
                        TreeItemSelected.Children.Add(treeItem);

                        UpdateFormTitle();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //增加数组节点
            AddArrayTreeItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    if (TreeItemSelected != null)
                    {
                        AddArrayTreeItemView addArrayTreeItemView = new AddArrayTreeItemView();
                        addArrayTreeItemView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        ViewShowPosition.SetShowPosition(addArrayTreeItemView).ShowDialog();
                        if (addArrayTreeItemView.DialogResult == false)
                        {
                            return;
                        }

                        AddArrayTreeItemViewModel addArrayTreeItemViewModel = addArrayTreeItemView.DataContext as AddArrayTreeItemViewModel;
                        string newArrayName = addArrayTreeItemViewModel.NewName;

                        //判断当前节点下有无节点
                        if (TreeItemSelected.Children == null)
                        {
                            TreeItemSelected.Children = new ObservableCollection<TreeItemStruct>();
                        }
                        TreeItemStruct treeItem = new TreeItemStruct { Name = $"{newArrayName}" };
                        treeItem.Parent = TreeItemSelected.Parent;
                        treeItem.IconName = "ApplicationArrayOutline";
                        treeItem.IsArray = true;


                        EnumDataType dataType = addArrayTreeItemViewModel.SelectedEnumValue;      //(EnumDataType)Enum.Parse(typeof(EnumDataType), );
                        object defaultValue = null;
                        switch (dataType)
                        {
                            case EnumDataType.Integer:
                                defaultValue = 0;
                                break;
                            case EnumDataType.String:
                                defaultValue = string.Empty;
                                break;
                            //case EnumDataType.Float:
                            case EnumDataType.Double:
                                defaultValue = 0.0;
                                break;
                            case EnumDataType.Boolean:
                                defaultValue = false;
                                break;
                            default:
                                break;
                        }
                        DataGridStruct dataGridStruct = new DataGridStruct();
                        for (int i = 0; i < addArrayTreeItemViewModel.ArrayLength; i++)
                        {
                            DataGridItemStruct dataGridItemStruct = new DataGridItemStruct();
                            dataGridItemStruct.Key = $"[{i}]";
                            dataGridItemStruct.Value = defaultValue;
                            dataGridItemStruct.Type = addArrayTreeItemViewModel.SelectedEnumValue;
                            dataGridStruct.DataGridItemStructs.Add(dataGridItemStruct);
                            treeItem.DataGridStructOfTreeItem = dataGridStruct;
                        }
                        TreeItemSelected.Parent.Children.Add(treeItem);

                        UpdateFormTitle();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });



            //增加子数组节点
            AddChildArrayTreeItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    if (TreeItemSelected != null)
                    {
                        AddArrayTreeItemView addArrayTreeItemView = new AddArrayTreeItemView();
                        addArrayTreeItemView.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                        ViewShowPosition.SetShowPosition(addArrayTreeItemView).ShowDialog();
                        if (addArrayTreeItemView.DialogResult == false)
                        {
                            return;
                        }

                        AddArrayTreeItemViewModel addArrayTreeItemViewModel = addArrayTreeItemView.DataContext as AddArrayTreeItemViewModel;
                        string newArrayName = addArrayTreeItemViewModel.NewName;

                        //判断当前节点下有无节点
                        if (TreeItemSelected.Children == null)
                        {
                            TreeItemSelected.Children = new ObservableCollection<TreeItemStruct>();
                        }

                        TreeItemStruct treeItem = new TreeItemStruct { Name = $"{newArrayName}" };
                        treeItem.Parent = TreeItemSelected;
                        treeItem.IconName = "ApplicationArrayOutline";
                        treeItem.IsArray = true;

                        EnumDataType dataType = addArrayTreeItemViewModel.SelectedEnumValue;
                        object defaultValue = null;
                        switch (dataType)
                        {
                            case EnumDataType.Integer:
                                defaultValue = 0;
                                break;
                            case EnumDataType.String:
                                defaultValue = string.Empty;
                                break;

                            //   case EnumDataType.Float:
                            case EnumDataType.Double:
                                defaultValue = 0.0;
                                break;
                            case EnumDataType.Boolean:
                                defaultValue = false;
                                break;
                            default:
                                break;
                        }
                        DataGridStruct dataGridStruct = new DataGridStruct();
                        for (int i = 0; i < addArrayTreeItemViewModel.ArrayLength; i++)
                        {
                            DataGridItemStruct dataGridItemStruct = new DataGridItemStruct();
                            dataGridItemStruct.Key = $"[{i}]";
                            dataGridItemStruct.Value = defaultValue;
                            dataGridItemStruct.Type = addArrayTreeItemViewModel.SelectedEnumValue;
                            dataGridStruct.DataGridItemStructs.Add(dataGridItemStruct);
                            treeItem.DataGridStructOfTreeItem = dataGridStruct;
                        }
                        TreeItemSelected.Children.Add(treeItem);

                        UpdateFormTitle();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });


            //复制树节点
            CopyTreeItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    Clipboard.Clear();
                    if (TreeItemSelected == null) return;
                    Clipboard.SetData("copyData", TreeItemSelected.Clone());

                    UpdateFormTitle();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //粘贴为同级树节点
            PasteAsTreeItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    TreeItemStruct tempData = Clipboard.GetData("copyData") as TreeItemStruct;
                    if (tempData == null) return;
                    tempData.Parent = TreeItemSelected.Parent;
                    TreeItemSelected.Parent.Children.Add(tempData);

                    UpdateFormTitle();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //粘贴为子级树节点
            PasteAsChildTreeItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    TreeItemStruct tempData = Clipboard.GetData("copyData") as TreeItemStruct;
                    if (tempData == null) return;
                    tempData.Parent = TreeItemSelected;
                    TreeItemSelected.Children.Add(tempData);

                    UpdateFormTitle();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });


            //重命名树节点
            RenameTreeItemCommand = new DelegateCommand((e) =>
            {
                TreeItemSelected.IsRename = true;
                //具体的重命名操作在MainView的cs文件中处理

            });


            //删除树节点
            DeleteTreeItemCommand = new DelegateCommand((e) =>
            {
                TreeItemSelected.Parent.Children.Remove(TreeItemSelected);

                UpdateFormTitle();
            });


            //向上移动
            MoveUpTreeItemCommand = new DelegateCommand((e) =>
            {
                int index = TreeItemSelected.Parent.Children.IndexOf(TreeItemSelected);
                if (index == 0)
                {
                    return;
                }
                TreeItemSelected.Parent.Children.Move(index, index - 1);

                UpdateFormTitle();
            });

            //向下移动
            MoveDownTreeItemCommand = new DelegateCommand((e) =>
            {
                int index = TreeItemSelected.Parent.Children.IndexOf(TreeItemSelected);
                if (index == TreeItemSelected.Parent.Children.Count - 1)
                {
                    return;
                }
                TreeItemSelected.Parent.Children.Move(index, index + 1);

                UpdateFormTitle();
            });


            //****************************   DataGrid 表格   *************************
            //添加一行  DataGridItemSelected
            AddDataGridItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    var addViewModel = new AddDataGridItemViewModel();
                    AddDataGridItemView addDataGridItemView = new AddDataGridItemView(addViewModel);
                    bool? result = ViewShowPosition.SetShowPosition(addDataGridItemView).ShowDialog();

                    if (result == false)
                    {
                        return;
                    }

                    //创建一个新的DataGridItemStruct对象，存储返回的数据
                    DataGridItemStruct dgs = new DataGridItemStruct();
                    dgs.Key = addViewModel.Key;
                    dgs.Value = addViewModel.Value;
                    dgs.Type = addViewModel.SelectedEnumValue;
                    dgs.ValueList.Add(dgs.Value);

                    // 多国语言注释
                    dgs.DataGridComments.LanguageComments.LanguageCommentsDic.Add("zh-CN", addViewModel.ChineseComment);
                    dgs.DataGridComments.LanguageComments.LanguageCommentsDic.Add("en-US", addViewModel.EnglishComment);
                    dgs.DataGridComments.LanguageComments.LanguageCommentsDic.Add("de-DE", addViewModel.GermanComment);

                    DataGridStructSelected.DataGridItemStructs.Add(dgs);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //复制行
            CopyDataGridItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    Clipboard.Clear();
                    var json = JsonConvert.SerializeObject(DataGridItemSelected.Clone());
                    Clipboard.SetText(json);
                    // Clipboard.SetData("copyData", DataGridItemSelected.Clone());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //粘贴行
            PasteDataGridItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    //DataGridItemStruct tempData = Clipboard.GetData("copyData") as DataGridItemStruct;
                    //if (tempData == null)
                    //{
                    //    return;
                    //}
                    //DataGridStructSelected.DataGridItemStructs.Add(tempData);
                    try
                    {
                        if (Clipboard.ContainsText())
                        {
                            var json = Clipboard.GetText();
                            var tempData = JsonConvert.DeserializeObject<DataGridItemStruct>(json);
                            if (tempData != null)
                            {
                                DataGridStructSelected.DataGridItemStructs.Add(tempData);
                            }
                        }
                        else
                        {
                            MessageBox.Show("剪贴板上的数据无效");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("剪贴板上的数据无效" + ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //删除行
            DeleteDataGridItemCommand = new DelegateCommand((e) => { DataGridStructSelected.DataGridItemStructs.Remove(DataGridItemSelected); });


            //向上移动
            MoveUpDataGridItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    int index = DataGridStructSelected.DataGridItemStructs.IndexOf(DataGridItemSelected);
                    if (index == 0)
                    {
                        return;
                    }
                    DataGridStructSelected.DataGridItemStructs.Move(index, index - 1);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //向下移动
            MoveDownDataGridItemCommand = new DelegateCommand((e) =>
            {
                try
                {
                    int index = DataGridStructSelected.DataGridItemStructs.IndexOf(DataGridItemSelected);
                    if (index == DataGridStructSelected.DataGridItemStructs.Count - 1)
                    {
                        return;
                    }
                    DataGridStructSelected.DataGridItemStructs.Move(index, index + 1);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //************* 数据编辑    ***********************
            //编辑值下拉列表
            EditValueListCommand = new DelegateCommand((e) =>
            {
                try
                {
                    if (DataGridItemSelected == null)
                    {
                        MessageBox.Show("请先选择一行数据进行编辑！");
                        return;
                    }
                    //EditValueListView editValueListView = new EditValueListView(DataGridItemSelected);
                    EditValueListView editValueListView = new EditValueListView(DataGridItemSelectedForEdit);
                    bool? result = ViewShowPosition.SetShowPosition(editValueListView).ShowDialog();
                    this.RaisePropertyChanged("DataGridItemSelectedForEdit");
                    //if (result == true)
                    //{
                    //    DataGridItemSelectedForEdit.ValueList = DataGridItemSelected.ValueList;
                    //}
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });

            //确认修改
            ConfirmCommand = new DelegateCommand((e) =>
            {
                try
                {
                    if (DataGridItemSelectedForEdit.Key != DataGridItemSelected.Key)
                    {
                        //设置Key变化是否触发    
                        DataGridItemSelected.CanRaiseKeyState = true;
                        //key值变化   DataGridStruct类中的DataGridItemStruct_PropertyChanged方法会被触发
                        DataGridItemSelected.Key = DataGridItemSelectedForEdit.Key;

                        //判断重命名是否成功   不允许命名时 不修改后面的值
                        if (!DataGridItemSelected.RenameState)
                        {
                            return;
                        }
                    }

                    DataGridItemSelected.Type = DataGridItemSelectedForEdit.Type;
                    DataGridItemSelected.Value = DataGridItemSelectedForEdit.Value;

                    DataGridItemSelected.ValueList = DataGridItemSelectedForEdit.ValueList;
                    DataGridItemSelected.TypeList = DataGridItemSelectedForEdit.TypeList;
                    DataGridItemSelected.ArrayIndex = DataGridItemSelectedForEdit.ArrayIndex;
                    DataGridItemSelected.DataGridComments = DataGridItemSelectedForEdit.DataGridComments;
                    DataGridItemSelected.HeaderIndex = DataGridItemSelectedForEdit.HeaderIndex;


                    //克隆最新的数据
                    DataGridItemStruct dgi = DataGridItemSelected.Clone();
                    //将当前数据的key值使用原始值
                    DataGridItemSelected.Key = DataGridItemSelected.OriginalKey;
                    //先删除再添加，达到更新的目的
                    DataGridStructSelected.DataGridItemStructs.Remove(DataGridItemSelected);
                    DataGridStructSelected.DataGridItemStructs.Add(dgi);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            });
        }

        private void AddJTokenToTreeView(JToken jToken, ref TreeItemStruct treeItem, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            try
            {
                switch (jToken.Type)
                {
                    case JTokenType.None:
                        break;
                    case JTokenType.Object:

                        DataGridItemStruct temp = null;
                        foreach (JProperty property in jToken.Children<JProperty>())
                        {
                            //判断当前键值对是否是注释
                            if (property.Name.Contains("#"))
                            {
                                if (temp == null)
                                {
                                    continue;
                                }
                                foreach (JProperty item in property.Value.Children<JProperty>())
                                {
                                    if (item.Name == "enum")
                                    {
                                        foreach (var val in item.Value)
                                        {
                                            temp.DataGridComments.ValueList.Add(TransData(val, val.Type));
                                        }
                                    }
                                    else
                                    {
                                        foreach (JProperty val in item.Value.Children<JProperty>())
                                        {
                                            switch (val.Name)
                                            {
                                                case "zh":
                                                    temp.DataGridComments.LanguageComments.LanguageCommentsDic["zh-CN"] = val.Value.ToString();
                                                    break;
                                                case "en":
                                                    temp.DataGridComments.LanguageComments.LanguageCommentsDic["en-US"] = val.Value.ToString();
                                                    break;
                                                case "de":
                                                    temp.DataGridComments.LanguageComments.LanguageCommentsDic["de-DE"] = val.Value.ToString();
                                                    break;
                                                default:
                                                    break;
                                            }
                                        }
                                    }
                                }
                                continue;
                            }

                            //判断当前键值对的值类型  不是JObject也不是JArray
                            if (property.Value.Type != JTokenType.Array && property.Value.Type != JTokenType.Object)
                            {
                                DataGridItemStruct dataGridItemStruct = new DataGridItemStruct();
                                dataGridItemStruct.Key = property.Name;

                                dataGridItemStruct.Value = TransData(property.Value, property.Value.Type);
                                dataGridItemStruct.ValueList = dataGridItemStruct.DataGridComments.ValueList;

                                //判断数据类型，为JTokenType.Float转换为double  
                                //将float转换为double  其他类型转换到对应枚举类型
                                if (property.Value.Type == JTokenType.Float)
                                {
                                    dataGridItemStruct.Type = EnumDataType.Double;
                                }
                                else
                                {
                                    dataGridItemStruct.Type = (EnumDataType)Enum.Parse(typeof(EnumDataType), property.Value.Type.ToString());
                                }


                                    //类型下拉列表绑定到枚举类，当前TypeList存放默认选中的值
                                    dataGridItemStruct.TypeList.Add(dataGridItemStruct.Type);
                                treeItem.DataGridStructOfTreeItem.DataGridItemStructs.Add(dataGridItemStruct);
                                temp = dataGridItemStruct;
                                continue;
                            }

                            //键值对的值为 JObject
                            TreeItemStruct treeChildItem = new TreeItemStruct();
                            treeChildItem.Name = property.Name;
                            treeChildItem.IconName = null;
                            //treeChildItem.ImagePath = "/Resources/Image/class.png";
                            treeChildItem.Parent = treeItem;
                            treeItem.Children.Add(treeChildItem);

                            AddJTokenToTreeView(property.Value, ref treeChildItem, out ErrorCode, out ErrorText);
                        }
                        break;
                    case JTokenType.Array:     // 数组
                        //treeItem.ImagePath = "/Resources/Image/array.png";
                        treeItem.IconName = "ApplicationArrayOutline";

                        treeItem.IsArray = true;
                        int Length = jToken.Count();
                        for (int i = 0; i < jToken.Count(); i++)
                        {
                            //判断数组中一个元素类型   判断数组中的元素 是类还是值
                            if (jToken[i].Type == JTokenType.Object)     //元素 是类
                            {
                                //遍历数组下的类元素
                                foreach (JProperty property in jToken[i].Children<JProperty>())
                                {
                                    TreeItemStruct treeChildItem = new TreeItemStruct();
                                    treeChildItem.Name = property.Name;
                                    // treeChildItem.ImagePath = "/Resources/Image/array.png";
                                    treeChildItem.IconName = "ApplicationArrayOutline";

                                    treeChildItem.Parent = treeItem;
                                    treeChildItem.IsArray = true;
                                    treeChildItem.ArrayIndex = i;
                                    treeItem.Children.Add(treeChildItem);
                                    AddJTokenToTreeView(property.Value, ref treeChildItem, out ErrorCode, out ErrorText);
                                }
                            }
                            else   //数组中元素 单个值
                            {
                                int index = 0;
                                foreach (var item in jToken)
                                {
                                    DataGridItemStruct dataGridItemStruct = new DataGridItemStruct();
                                    dataGridItemStruct.Key = $"[{index}]";
                                    dataGridItemStruct.Value = TransData(item, item.Type);

                                    dataGridItemStruct.ValueList = dataGridItemStruct.DataGridComments.ValueList;
                                    // dataGridItemStruct.ValueList.Add(dataGridItemStruct.Value);
                                    //将float转换为double  其他类型转换到对应枚举类型
                                    if (item.Type == JTokenType.Float)
                                    {
                                        dataGridItemStruct.Type = EnumDataType.Double;
                                    }
                                    else
                                    {
                                        dataGridItemStruct.Type = (EnumDataType)Enum.Parse(typeof(EnumDataType), item.Type.ToString());
                                    }

                                    dataGridItemStruct.TypeList.Add(dataGridItemStruct.Type);
                                    treeItem.DataGridStructOfTreeItem.DataGridItemStructs.Add(dataGridItemStruct);
                                    index++;

                                    JProperty property = (JProperty)jToken.Parent.Next;
                                    if (property.Name.Contains("#"))
                                    {
                                        foreach (JProperty jp in property.Value.Children<JProperty>())
                                        {
                                            if (jp.Name == "enum")
                                            {
                                                foreach (var val in jp.Value)
                                                {
                                                    dataGridItemStruct.DataGridComments.ValueList.Add(TransData(val, val.Type));
                                                }
                                            }
                                            else
                                            {
                                                foreach (JProperty val in jp.Value.Children<JProperty>())
                                                {
                                                    switch (val.Name)
                                                    {
                                                        case "zh":
                                                            dataGridItemStruct.DataGridComments.LanguageComments.LanguageCommentsDic["zh-CN"] = val.Value.ToString();
                                                            break;
                                                        case "en":
                                                            dataGridItemStruct.DataGridComments.LanguageComments.LanguageCommentsDic["en-US"] = val.Value.ToString();
                                                            break;
                                                        case "de":
                                                            dataGridItemStruct.DataGridComments.LanguageComments.LanguageCommentsDic["de-DE"] = val.Value.ToString();
                                                            break;
                                                        default:
                                                            break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                break;
                                //  AddJTokenToTreeView(jToken[i], ref treeItem, out ErrorCode, out ErrorText);
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "AddJTokenToTreeView Fail！" + ex.Message;
            }
        }

        private object TransData(JToken value, JTokenType dataType)
        {
            switch (dataType)
            {
                case JTokenType.Integer: return (int)value;
                case JTokenType.Float:
                    //若json数据类型为float则判断到底是float还是double，因为该枚举向外只暴露float
                    Type type = ((JValue)value).Value.GetType();
                    switch (type.ToString())
                    {
                        case "System.Single":
                            if (float.TryParse(value.ToString(), out float floatValue))
                            {
                                return floatValue;
                            }
                            break;
                        case "System.Double":

                            // 尝试转换为 double
                            if (double.TryParse(value.ToString(), out double doubleValue))
                            {
                                return doubleValue;
                            }
                            break;
                        default:
                            break;
                    }
                    return (float)value;
                case JTokenType.String: return value.ToString();
                case JTokenType.Boolean: return (bool)value;

                default: return (int)value;
            }
        }

        public void TraverseTreeItem(TreeItemStruct treeItem, JToken token)
        {
            try
            {

                foreach (var itemChild in treeItem.Children)
                {
                    //不是数组
                    if (!itemChild.IsArray)
                    {
                        JObject jObjectTreeItem = new JObject();
                        JProperty jPropertyTreeItem = new JProperty(itemChild.Name, jObjectTreeItem);
                        ((JObject)token).Add(jPropertyTreeItem);
                        //itemChild不是数组，DataGridItemStructs中数据为键值对
                        foreach (DataGridItemStruct dataGridItem in itemChild.DataGridStructOfTreeItem.DataGridItemStructs)
                        {

                            //将值转换成对用数据类型存储到json数组    
                            TranDataByType(dataGridItem.Type, dataGridItem.Value, out object outValue);
                            //创建键值对
                            JProperty jPropertyDataGridItem = new JProperty(dataGridItem.Key, outValue);

                            // JObject jObjectDataGridItem = new JObject(jPropertyDataGridItem);
                            jObjectTreeItem.Add(jPropertyDataGridItem);


                            //=====创建注释======
                            JObject jbComment = new JObject();
                            JProperty jPropertyComment = new JProperty("#" + dataGridItem.Key, jbComment);

                            //创建下拉列表的注释
                            JArray jArray = new JArray();
                            foreach (var value in dataGridItem.DataGridComments.ValueList)
                            {
                                jArray.Add(value);
                            }
                            JProperty jPropertyValueList = new JProperty("enum", jArray);
                            jbComment.Add(jPropertyValueList);


                            JProperty jPropertyDataGridChineseComment = new JProperty("zh", dataGridItem.DataGridComments.LanguageComments.LanguageCommentsDic["zh-CN"]);
                            JProperty jPropertyDataGridEnglishComment = new JProperty("en", dataGridItem.DataGridComments.LanguageComments.LanguageCommentsDic["en-US"]);
                            JProperty jPropertyDataGridGermanComment = new JProperty("de", dataGridItem.DataGridComments.LanguageComments.LanguageCommentsDic["de-DE"]);

                            JObject jb = new JObject();
                            jb.Add(jPropertyDataGridChineseComment);
                            jb.Add(jPropertyDataGridEnglishComment);
                            jb.Add(jPropertyDataGridGermanComment);
                            JProperty jPropertyLanguage = new JProperty("lan", jb);
                            jbComment.Add(jPropertyLanguage);
                            jObjectTreeItem.Add(jPropertyComment);
                        }
                        TraverseTreeItem(itemChild, jObjectTreeItem);
                    }

                    //是数组
                    else
                    {
                        JArray jArrayTreeItem = new JArray();
                        JProperty jPropertyDataGridItem = new JProperty(itemChild.Name, jArrayTreeItem);
                        if (token.Type == JTokenType.Array)
                        {
                            ((JArray)token).Add(new JObject(jPropertyDataGridItem));
                        }
                        else if (token.Type == JTokenType.Object)
                        {
                            ((JObject)token).Add(jPropertyDataGridItem);
                        }
                        foreach (DataGridItemStruct dataGridItem in itemChild.DataGridStructOfTreeItem.DataGridItemStructs)
                        {
                            //将值转换成对用数据类型存储到json数组    
                            TranDataByType(dataGridItem.Type, dataGridItem.Value, out object outValue);
                            jArrayTreeItem.Add(outValue);
                        }

                        //=====创建注释======
                        JObject jbComment = new JObject();
                        JProperty jPropertyComment = new JProperty("#" + itemChild.Name, jbComment);

                        //创建下拉列表的注释
                        JArray jArray = new JArray();
                        foreach (var value in itemChild.DataGridStructOfTreeItem.DataGridItemStructs[0].DataGridComments.ValueList)
                        {
                            jArray.Add(value);
                        }
                        JProperty jPropertyValueList = new JProperty("enum", jArray);
                        jbComment.Add(jPropertyValueList);

                        //数组元素不设置多国语言注释
                        //JProperty jPropertyDataGridChineseComment = new JProperty("zh", itemChild.DataGridStructOfTreeItem.DataGridItemStructs[0].DataGridComments.LanguageComments.LanguageCommentsDic["zh-CN"]);
                        //JProperty jPropertyDataGridEnglishComment = new JProperty("en", itemChild.DataGridStructOfTreeItem.DataGridItemStructs[0].DataGridComments.LanguageComments.LanguageCommentsDic["en-US"]);
                        //JProperty jPropertyDataGridGermanComment = new JProperty("de", itemChild.DataGridStructOfTreeItem.DataGridItemStructs[0].DataGridComments.LanguageComments.LanguageCommentsDic["de-DE"]);

                        //JObject jb = new JObject();
                        //jb.Add(jPropertyDataGridChineseComment);
                        //jb.Add(jPropertyDataGridEnglishComment);
                        //jb.Add(jPropertyDataGridGermanComment);
                        //JProperty jPropertyLanguage = new JProperty("lan", jb);
                        //jbComment.Add(jPropertyLanguage);

                        ((JObject)token).Add(jPropertyComment);

                        TraverseTreeItem(itemChild, jArrayTreeItem);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void TranDataByType(EnumDataType enumDataType, object value, out object outValue)
        {
            outValue = null;
            try
            {
                //将值转换成对用数据类型存储到json数组
                switch (enumDataType)
                {
                    //case EnumDataType.Float:
                    //    outValue = Convert.ToSingle(value);
                    //    break;
                    case EnumDataType.Integer:
                        outValue = Convert.ToInt32(value);
                        break;
                    case EnumDataType.String:
                        outValue = Convert.ToString(value);
                        break;
                    case EnumDataType.Double:
                        outValue = Convert.ToDouble(value);
                        break;
                    case EnumDataType.Boolean:
                        outValue = Convert.ToBoolean(value);
                        break;
                    default:
                        outValue = null;
                        break;
                }
            }
            catch (Exception ex)
            {

            }
          
        }
        public void SaveFile(string filePath, JToken jToken, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            try
            {
                string jsonData = JsonConvert.SerializeObject(jToken);
                //  string jsonData = jToken.ToString(Newtonsoft.Json.Formatting.Indented);
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter(fs))
                    {
                        streamWriter.Write(jsonData);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "SaveFile Fail！" + ex.Message;
            }
        }
        public JToken LoadFile(string filePath, out int ErrorCode, out string ErrorText)
        {
            ErrorCode = 0;
            ErrorText = "NoError";
            try
            {
                string jsonText;
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    //编码使用UTF8，GB2312有出现乱码的情况
                    using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8))
                    {
                        jsonText = streamReader.ReadToEnd();
                    }
                }
                JToken _jToken = JsonConvert.DeserializeObject<JToken>(jsonText);
                //JToken _jToken = JToken.Parse(jsonText);
                return _jToken;
            }
            catch (Exception ex)
            {
                ErrorCode = -1;
                ErrorText = "LoadFile Fail！" + ex.Message;
                return null;
            }
        }
    }
}
